package com.example.controller;

import com.example.pojo.*;
import com.example.service.ForumReplyService;
import com.example.service.ForumService;
import com.example.service.ForumTopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author 二七和夭夭
 * @email 2646498606@qq.com
 * @date 2022/8/23 17:36
 */
@Controller
@RequestMapping("/topic")
public class ForumTopicController {
    @Autowired
    private ForumTopicService forumTopicService;
    @Autowired
    private ForumReplyService forumReplyService;
    @Autowired
    private ForumService forumService;

    /**
     * 展示具体话题页面
     *
     * @return
     */
    @RequestMapping("/showReply.do")
    public String showReply(Integer tid, Model model, Integer currentPage, Integer pageSize) {
        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageSize == null) {
            pageSize = 5;
        }
        //根据id查询topic
        List<ForumTopic> topicList = forumTopicService.getForumTopics(tid);
        ForumTopic topic = topicList.get(0);
        model.addAttribute("topic", topic);

        //查询topic下的reply(使用PageBean包装)
        PageBean<ForumReply> pageBean = forumReplyService.getReplyByPage(currentPage, pageSize, tid);
        model.addAttribute("pageBean", pageBean);
        return "/jsp/topic/showReply.jsp";
    }

    /**
     * 前往添加页面
     *
     * @return
     */
    @RequestMapping("/addUI.do")
    public String toAddUI(Integer forumId, Model model) {
        //查询forum
        List<Forum> list = forumService.getList(forumId);
        Forum forum = list.get(0);
        model.addAttribute("forum", forum);

        return "/jsp/topic/add.jsp";
    }

    /**
     * 添加主题并且修改论坛信息
     * @return
     */
    @RequestMapping("/add.do")
    public String addTopic(HttpServletRequest req,Integer forumId, Integer topicCount,
                           Integer articleCount, String title, String content) {
        // 获取登录用户
        User user = (User) req.getSession().getAttribute("loginUser");

        //包装新增对象
        ForumTopic forumTopic = new ForumTopic();
        forumTopic.setTitle(title);
        forumTopic.setContent(content);
        forumTopic.setPostTime(new Date());
        forumTopic.setAuthorId(user.getUid());
        forumTopic.setIpAddress("127.0.0.1");//添加ip地址(不会 直接写)
        forumTopic.setLastUpdateTime(new Date());
        //设置主题类型  0表示普通帖 1表示精华帖 2表示置顶帖
        forumTopic.setType(0);
        forumTopic.setForumId(forumId);
        forumTopic.setReplyCount(0);
        forumTopic.setLastReplyId(0);

        //添加主题并且修改论坛信息
        forumTopicService.saveTopic(forumTopic,forumId,topicCount,articleCount);

        return "redirect:/forum/show.do?fid="+forumId;
    }
}
